package com.gzx.asr.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class FunAsrConfig {
    public static JSONObject initConfig(String mode, String strChunkSize, int chunkInterval, String wavName, boolean isSpeaking, String suffix, String hotwords) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("mode", mode);
            JSONArray array = new JSONArray();
            String[] chunkList = strChunkSize.split(",");
            for (int i = 0; i < chunkList.length; i++) {
                array.add(Integer.valueOf(chunkList[i].trim()));
            }

            obj.put("chunk_size", array);
            obj.put("chunk_interval", (int) (chunkInterval));
            obj.put("wav_name", wavName);

            if (hotwords.trim().length() > 0) {
                String regex = "\\d+";
                JSONObject jsonitems = new JSONObject();
                String[] items = hotwords.trim().split(" ");
                Pattern pattern = Pattern.compile(regex);
                String tmpWords = "";
                for (int i = 0; i < items.length; i++) {

                    Matcher matcher = pattern.matcher(items[i]);

                    if (matcher.matches()) {

                        jsonitems.put(tmpWords.trim(), items[i].trim());
                        tmpWords = "";
                        continue;
                    }
                    tmpWords = tmpWords + items[i] + " ";

                }
                obj.put("hotwords", jsonitems.toString());
            }

            if (suffix.equals("wav")) {
                suffix = "pcm";
            }
            obj.put("wav_format", suffix);
            if (isSpeaking) {
                obj.put("is_speaking", true);
            } else {
                obj.put("is_speaking", false);
            }

            log.info("sendJson: " + obj);
            return obj;
        } catch (Exception e) {
            log.error("发送消息的参数非法: " + e);
            return null;
        }
    }
}
